<?php

namespace app\wechat;

use think\Request;
use think\Controller;
use app\model\Conf as ConfModel;
use app\model\Wechat as WechatModel;

class Base extends Controller
{
    protected $request;
    protected $module;
    protected $controller;
    protected $action;
    protected $domain;

    protected $openid;
    protected $appLongid;
    protected $wechat;
    protected $access_token;

    protected $ConfModel;
    protected $WechatModel;
    public function __construct()
    {
        header('Access-Control-Allow-Origin: *'); //允许所有来源访问
        header('Access-Control-Allow-Methods: POST'); //响应类型
        $this->ConfModel = new ConfModel();
        $this->WechatModel = new WechatModel();

        $configs = $this->ConfModel->select();
        $c = [];
        foreach ($configs as $config) {
            $c[$config['conf_key']] = $config['conf_value'];
        }
        config($c);
        $this->init();
    }
    protected function init()
    {
        $this->request = Request::instance();
        $this->module = strtolower($this->request->module()) ? strtolower($this->request->module()) : "admin";
        $this->controller = $this->request->controller() ? $this->request->controller() : "Index";
        $this->action = strtolower($this->request->action()) ? strtolower($this->request->action()) : "index";
        $this->domain = $this->request->domain();
        $this->access_token = $this->ConfModel->getAccessToken();
    }
    public function _empty($name)
    {
        $this->error("操作方法不存在($name)");
    }
    public function response()
    {
        $postStr = file_get_contents("php://input");
        // file_put_contents("./wechat.xml",$postStr);
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->openid = trim($postObj->FromUserName);
            $this->appLongid = trim($postObj->ToUserName);
            $this->wechat = $this->login($this->openid);
            $msgType = trim($postObj->MsgType);
            if ($msgType == "text") {
                $keyword = trim($postObj->Content);
                //TODO wtext model
                switch ($keyword) {
                    case "首页":
                        break;
                    default:
                        $this->echoText($keyword);
                }
                exit;
            } else if ($msgType == "event") {
                $event = trim($postObj->Event);
                if ($event == "subscribe") {
                    $eventKey = trim($postObj->EventKey);
                    if (empty($eventKey)) {
                        $text = config("welcome_text");
                        if (empty($text)) {
                            $this->echoText("请在后台配置默认回复内容！");
                        } else {
                            $this->echoText($text);
                        }
                    } else {
                        $eventKey = str_replace("qrscene_", "", $eventKey);
                        $this->doScanQrcode($eventKey);
                    }
                } else if ($event == "CLICK") {
                    $eventKey = trim($postObj->EventKey);
                    //TODO wclick model
                    switch ($eventKey) {
                        case '菜单名称':
                            break;
                        default:
                            $this->echoText($eventKey);
                    }
                } else if ($event == "SCAN") {
                    $eventKey = trim($postObj->EventKey);
                    $this->doScanQrcode($eventKey);
                } else if ($event == "scancode_waitmsg") {
                    $scanResult = trim($postObj->ScanCodeInfo->ScanResult);
                    $this->echoText($scanResult);
                } else if ($event == "LOCATION") {
                    $this->echoText("位置已经获取到了！");
                } else {
                    $this->echoText("暂不支持的事件" . $event);
                }
            } else if ($msgType == "voice") {
                //语音
                $keyword = trim($postObj->Recognition);
                $MediaId = ($postObj->MediaId);
                $textTemp = "<xml><ToUserName><![CDATA[" . $this->openid . "]]></ToUserName><FromUserName><![CDATA[" . $this->appLongid . "]]></FromUserName><CreateTime>" . time() . "</CreateTime><MsgType><![CDATA[voice]]></MsgType><Voice><MediaId><![CDATA[" . $MediaId . "]]></MediaId></Voice></xml>";
                echo $textTemp;
                exit;
            } else if ($msgType == "image") {
                //图片
                $MediaId = ($postObj->MediaId);
                $textTemp = "<xml><ToUserName><![CDATA[" . $this->openid . "]]></ToUserName><FromUserName><![CDATA[" . $this->appLongid . "]]></FromUserName><CreateTime>" . time() . "</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[" . $MediaId . "]]></MediaId></Image></xml>";
                echo $textTemp;
                exit;
            } else {
                $this->echoText("暂不支持的消息类型" . $msgType);
            }
        } else {
            echo input("get.echostr");
            die();
        }
    }
    protected function doScanQrcode($eventKey)
    {
        $qrData = json_decode(urldecode($eventKey));
        switch ($qrData->type) {
            case "desk":
                //TODO
                //                $qrData->id;
                break;
            default:
                $this->echoText("该二维码暂时无法解析");
                exit;
        }
    }
    protected function login($openid)
    {
        $retStr = httpGetFull("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->access_token . "&openid={$openid}&lang=zh_CN");
        $retObj = json_decode($retStr);
        if (property_exists($retObj, "errorcode")) {
            return null;
        } else {
            // print_r($retObj);exit;
            $nickname = urlencode($retObj->nickname);
            $sex = urlencode($retObj->sex);
            $headimgurl = urlencode($retObj->headimgurl);
            $this->wechat = $this->WechatModel->getWechatByOpenid($openid)->find();
            if (!$this->wechat) {
                //注册
                $data = ["wechat_openid" => $openid, "wechat_nick" => $nickname, "wechat_head" => $headimgurl, "wechat_sex" => $sex, "wechat_createtime" => time(), "wechat_updatetime" => time()];
                $this->WechatModel->insert($data);
            } else {
                //更新
                $this->WechatModel->where('wechat_openid', $openid)->update(["wechat_nick" => $nickname, "wechat_head" => $headimgurl, "wechat_sex" => $sex, "wechat_updatetime" => time()]);
            }
            $this->wechat = $this->WechatModel->getWechatByOpenid($openid)->find();
        }
    }

    protected function keywordReplace($keyword)
    {
        $keyword = str_replace("。", "", $keyword);
        return $keyword;
    }
    protected function echoText($msg = "【系统错误】\n\n输出参数错误！")
    {
        $textTemp = "<xml><ToUserName><![CDATA[" . $this->openid . "]]></ToUserName><FromUserName><![CDATA[" . $this->appLongid . "]]></FromUserName><CreateTime>" . time() . "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" . $msg . "]]></Content></xml>";
        echo $textTemp;
        exit;
    }
}
